package data

import (
	"context"
	"user/internal/conf"
	"user/internal/data/ent"

	"github.com/go-kratos/kratos/v2/log"
	_ "github.com/go-sql-driver/mysql"
	"github.com/google/wire"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(
	NewEntClient,
	NewData,
	NewUserRepo,
)

// Data .
type Data struct {
	// TODO wrapped database client
	entClient *ent.Client
}

// NewData .
func NewData(entClient *ent.Client, logger log.Logger) (*Data, func(), error) {
	cleanup := func() {
		entClient.Close() // 关闭 Ent 客户端
		log.NewHelper(logger).Info("closing the data resources")
	}
	return &Data{
		entClient: entClient, // 保存 Ent 客户端
	}, cleanup, nil
}

func NewEntClient(c *conf.Data) (*ent.Client, func(), error) {
	client, err := ent.Open(
		c.Database.Driver,
		c.Database.Source,
	)
	if err != nil {
		return nil, nil, err // 返回错误，而不是直接终止
	}

	// 运行自动迁移工具。
	if err := client.Schema.Create(context.Background()); err != nil {
		return nil, nil, err // 返回错误，而不是直接终止
	}

	return client, func() { _ = client.Close() }, nil
}
